package mobi.smarthosts;

import java.util.Date;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.preference.PreferenceManager;

public class CheckingUpdateService extends Service implements DownloadHostsTask.TaskHandler {

    public static final String ACTION_CHECK_UPDATE = "action_check_update";

    private NotificationManager mNotificationManager;
    private Configuration mConf;
    private SharedPreferences mPref;

    //*************************************************************************
    // Overridden Methods
    //*************************************************************************

    @Override
    public void onCreate() {
        mConf = Configuration.getInstance();
        mPref = PreferenceManager.getDefaultSharedPreferences(this);
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    // This is the old onStart method that will be called on the pre-2.0
    // platform.  On 2.0 or later we override onStartCommand() so this
    // method will not be called.
    @Override
    public void onStart(Intent intent, int startId) {
        handleStartCommand(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        handleStartCommand(intent);
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_NOT_STICKY;
    }

    private void handleStartCommand(Intent intent) {
        // if (intent == null) return; // Avoid system start signal.
        Log.i("Starting Server Connection Service for action :: " + intent.getAction());

        // Handle update app notification action.
        if (ACTION_CHECK_UPDATE.equals(intent.getAction())) {
            Log.i("Checking update for hosts at %s", mConf.getUpdateSiteUrl(this));
            DownloadHostsTask task = new DownloadHostsTask(this, false);
            task.execute();
            return;
        }
    }

    @Override
    public void onDownloadCompleted(Hosts[] hostsArray) {
        if (Utils.isEmptyArray(hostsArray)) return;
        // Error should has been reported by DownloadHostsTask

        // Check new download hosts with last download version
        String lastUpdateMd5 = mPref.getString(PrefKeys.KEY_LAST_UPDATE_MD5, null);
        long lastUpdateDateLong = mPref.getLong(PrefKeys.KEY_LAST_UPDATE_DATE, 0);
        Date lastUpdateDate = lastUpdateDateLong != 0 ? new Date(lastUpdateDateLong) : null;
        boolean noUpdate = ((lastUpdateMd5 != null && hostsArray[0].md5.equals(lastUpdateMd5))
                         || (lastUpdateDate != null && hostsArray[0].updateDate != null
                                 && hostsArray[0].updateDate.equals(lastUpdateDate)));

        // If no update, alert user
        if (!noUpdate) notifyUpdates();
    }

    public void notifyUpdates() {
        String title = getString(R.string.msg_hasUpdate);
        Notification notify = new Notification(R.drawable.ic_launcher,
                title, System.currentTimeMillis());
        PendingIntent contentIntent =
            PendingIntent.getActivity(this, 0, new Intent(this, HomeActivity.class), 0);
        notify.setLatestEventInfo(this, title, null, contentIntent);
        mNotificationManager.notify(R.string.msg_hasUpdate, notify);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}
